﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Consul;

namespace MicroContainers.AspCore.Consul.ServiceDiscovery
{
    internal class ConsulService
    {
        internal ServiceIdentity Identity { get; set; }

        internal string[] Urls { get; private set; }

        internal int Index { get; private set; }

        internal string Get()
        {
            return Urls[Index];
        }

        internal string GetNext()
        {
            Index++;
            if (Index >= Urls.Length)
                Index = 0;
            return Get();
        }

        internal void Init(Dictionary<string, AgentService> services)
        {
            var urls = new List<string>();

            foreach (var agentService in services)
            {
                var isService = Identity.Tags.Select(t => agentService.Value.Tags.Any(x => x == t)).All(r => r);
                if (isService)
                {
                    urls.Add($"{agentService.Value.Address}:{agentService.Value.Port}");
                }
            }

            Urls = urls.ToArray();
        }
    }
}
